package com.ask.forMe.controller.ai;

import com.ask.forMe.langchain4j.agent.MyAgentMemory;
import com.ask.forMe.langchain4j.agent.DocxMarkHeadingAgent;
import com.ask.forMe.langchain4j.agent.XiaozhiAgent;
import com.ask.forMe.langchain4j.service.EmbeddingService;
import com.ask.forMe.langchain4j.service.ContextService;
import com.ask.forMe.langchain4j.service.PrivacyProtectionService;
import com.ask.forMe.model.dto.ChatForm;
import com.ask.forMe.model.dto.CustomerServiceContext;
import dev.langchain4j.model.openai.OpenAiChatModel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.Arrays;

import static com.ask.forMe.constant.CustomerSupportConstants.EMOTION_SCORE_THRESHOLD;
import static com.ask.forMe.constant.CustomerSupportConstants.REPEAT_COUNT_THRESHOLD;

@Slf4j
@RestController
@RequestMapping("/xiaozhi")
@Tag(name = "智能体聊天接口")
public class AgentController {

    @Autowired
    private MyAgentMemory myAgentMemory;

    @Autowired
    private XiaozhiAgent xiaozhiAgent;

    @Autowired
    private DocxMarkHeadingAgent myAgentNoMemory;

    @Autowired
    private OpenAiChatModel openAiChatModel;

    @Autowired
    private ContextService contextService;


    @Autowired
    private PrivacyProtectionService privacyProtectionService;
    @Autowired
    private EmbeddingService embeddingService;

    @GetMapping("/noMemory")
    @Operation(summary = "1.无记忆聊天模型")
    public String chatNoMemory(String userMessage) {
        return myAgentNoMemory.chat(userMessage);
    }

    @GetMapping("/memory")
    @Operation(summary = "2.记忆聊天模型")
    public String chat(@RequestParam(defaultValue = "我是谁") String message, Integer userId) {
        return myAgentMemory.chat(userId, message);
    }


    @PostMapping("/xiaozhi_chat")
    @Operation(summary = "3.小智对话")
    public String xiaozhiChat(@RequestParam(defaultValue = "我是谁") String message, String userId) {
        // 输入脱敏
        message = privacyProtectionService.maskSensitiveInfo(message);
        // 查询高频问题答案
        String ans = embeddingService.querySimilarQuestions(message);
        if (ans != null) return ans;
        // 模型返回输出
        String output = xiaozhiAgent.chat(userId, message);
        // 提取对话上下文
        CustomerServiceContext context = contextService.extractContext(output, userId);
        log.info("本轮对话上下文：{}", context);
        return output;
    }

    @PostMapping(value = "/chat", produces = "text/stream;charset=utf-8")
    @Operation(summary = "4.小智流式对话")
    public String xiaozhiChatStream(@RequestBody ChatForm chatForm) {
        // 输入脱敏
        String message = chatForm.getMessage();
        message = privacyProtectionService.maskSensitiveInfo(message);
        // 查询高频问题答案
        String ans = embeddingService.querySimilarQuestions(message);
        if (ans != null) return ans;
        // 返回模型输出
        String output = xiaozhiAgent.chat(chatForm.getMemoryId(), chatForm.getMessage());
        // 提取上下文
        CustomerServiceContext context = contextService.extractContext(output, chatForm.getMemoryId().toString());
        if (context.getEmotionScore() < EMOTION_SCORE_THRESHOLD || context.getRepeatCount() > REPEAT_COUNT_THRESHOLD) {
            // 上下文传递给人工客服
            // 返回提示信息
            System.out.println("用户情绪分数达到阈值，转接人工客服......");
            return "为您转接人工客服，请稍等....";
        }
        return output;
    }

    @GetMapping("deepSeek")
    @Operation(summary = "deepSeek模型测试")
    public String deepSeekTest(String message) {
        return openAiChatModel.chat(message);
    }

    @GetMapping("/flux")
    @Operation(summary = "flux测试")
    public Flux<String> generateResponse(String prompt) {
        // 这里可以是调用AI模型、数据库查询或其他业务逻辑
        return Flux.fromIterable(Arrays.asList(
                        "基于您的问题：\"" + prompt + "\"，",
                        "我们正在生成回答...",
                        "首先，需要考虑的是...",
                        "其次，可以这样处理...",
                        "最后，建议您..."
                ))
                .delayElements(Duration.ofMillis(700));
    }
}
